package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"gopkg.in/gomail.v2"
	"strconv"
)

type Weath struct {
	Msg	string
	Times []string
	Values []float32
	Ph string
	Time string
	Uptime string
	Status string
}

type Sk struct{
	WS string
	WD string
	Temp string
	Weather string
	Humidity string
}

func Sendemail(mailTo []string, subject string, body string) error {
	mainConn := map[string]string{
		"user":"718358058@qq.com",
		"pass":"wrbwgucobjsabead",
		"host":"smtp.qq.com",
		"port":"465",
	}
	port, _ := strconv.Atoi(mainConn["port"])
	m := gomail.NewMessage()
	m.SetHeader("Received"," from 718358058@qq.com ")
	m.SetHeader("From", m.FormatAddress(mainConn["user"], "xiaogs"))
	m.SetHeader("To",mailTo...)
	m.SetHeader("Subject",subject)
	m.SetBody("text/plain",body)
	d := gomail.NewDialer(mainConn["host"],port,mainConn["user"],mainConn["pass"])
	err := d.DialAndSend(m)
	return err
}
//
//http://forecast.weather.com.cn/town/api/v1/sk?lat=22.754428&lng=114.458009
func main(){
	mailTo := []string{
		"718358058@qq.com",
		"1225218575@qq.com",
	}
	resp,err := http.Get("http://d3.weather.com.cn/webgis_rain_new/webgis/minute?lat=22.754428&lon=114.458009")
	if err != nil {
		log.Println(err)
	}
	defer resp.Body.Close()
	body,err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println(err)
	}
	w := &Weath{}
	err = json.Unmarshal(body,w)
	if err != nil {
		log.Println(err)
	}
	fmt.Println(w)
	ms := w.Msg

	resp,err = http.Get("http://forecast.weather.com.cn/town/api/v1/sk?lat=22.754428&lng=114.458009")
	
	if err != nil {
		log.Println(err)
	}
	defer resp.Body.Close()
	body,err = ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println(err)
	}

	sk := &Sk{}
	err = json.Unmarshal(body,sk)
	if err != nil {
		log.Println(err)
	}
	fmt.Println(sk)

	ms += fmt.Sprintf("\r\n天气：%s  气温：%s℃  湿度：%s  风力：%s  风向：%s",sk.Weather,sk.Temp,sk.Humidity,sk.WS,sk.WD)

	for key, value := range w.Values {
		if value > 0 {
			ms += fmt.Sprintf("\r\n在%s时，有%d%%的概率下雨",w.Times[key],(int)(value*100))
		}
	}




	Sendemail(mailTo,"天气预报",ms)
}